<template>
  <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px">
    <el-form-item prop="avatarUrl" label="头像">
      <AvatarUpload v-model="dataForm.avatarUrl" />
    </el-form-item>
    <el-form-item prop="nickname" label="昵称">
      <el-input v-model="dataForm.nickname" placeholder="昵称" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="handleDataForm">{{ $t('confirm') }}</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import { useUserStore } from '@/store/user'

import type { InfoDTO } from '@/store/user/data.d'
import type { FormInstance, FormRules } from 'element-plus'

import AvatarUpload from '@/components/AvatarUpload/index.vue'

const { t } = useI18n()

const userStore = useUserStore()

const dataFormRef = ref<FormInstance>()

const dataForm = reactive<InfoDTO>({
  nickname: userStore.user.nickname,
  avatarUrl: userStore.user.avatarUrl || '',
  password: userStore.user.nickname,
})

const dataRules = reactive<FormRules<InfoDTO>>({
  nickname: [{ required: true, message: t('required'), trigger: 'blur' }],
  password: [{ required: true, message: t('required'), trigger: 'blur' }],
})

const handleDataForm = () => {
  dataFormRef.value!.validate((valid) => {
    if (!valid) return

    // 修改登录用户信息
    userStore.updateInfoAction(dataForm).then((res) => {
      if (!res) return
      // 更新状态管理
      userStore.user.nickname = dataForm.nickname
    })
  })
}
</script>
<style lang="scss" scoped>
:deep().el-upload {
  --display: flex;
  display: var(--display);
}
</style>
